<template>
  <div class="goods-image">
    <!-- 放大图 -->
    <div class="large" v-show="!isOutside" >
      <img :src="images[activeIndex]" alt="" :style="{ left: largeImg.x, top: largeImg.y }"/>
    </div>
    <!-- 主图，展示图 -->
    <div class="middle" ref="target">
      <img :src="images[activeIndex]" alt="" />
      <div class="layer" v-show="!isOutside" :style="{ left: layer.x, top: layer.y }"></div>
    </div>
    <!-- 列表图片 -->
    <ul class="small">
      <li
        v-for="(item, index) in images"
        :key="index"
        @mouseenter="activeIndex = index"
      >
        <img :src="item" alt="" />
      </li>
    </ul>
  </div>
</template>

<script>
import { reactive, ref, watch } from 'vue'
import { useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  props: {
    images: {
      type: Array,
      default: () => []
    }
  },
  setup () {
    const activeIndex = ref(0)
    const target = ref(null)

    const { elementX, elementY, isOutside } = useMouseInElement(target)
    // 遮幕的定位
    const layer = reactive({ x: 0, y: 0 })
    // 放大图的定位
    const largeImg = reactive({ x: 0, y: 0 })
    // 侦听鼠标在目标位置的移动变化
    watch([elementX, elementY], () => {
    //   console.log(elementX, elementY, isOutside)
    // 鼠标的定位
      layer.x = elementX.value - 100
      layer.y = elementY.value - 100
      //   限制的移动范围
      if (layer.x < 0) layer.x = 0
      if (layer.y < 0) layer.y = 0
      if (layer.x > 200) layer.x = 200
      if (layer.y > 200) layer.y = 200

      // 放大图的移动位置
      largeImg.x = -2 * layer.x + 'px'
      largeImg.y = -2 * layer.y + 'px'
      // 遮幕的移动位置
      layer.x += 'px'
      layer.y += 'px'
    })

    return { activeIndex, layer, isOutside, largeImg, target }
  }
}
</script>

<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
    // 大图预览
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
    overflow: hidden;
    z-index: 401;
    img {
      max-width: 800px;
      max-height: 800px;
      width: 800px;
      height: 800px;
      position: absolute;
      left: 0;
      top: 0;
    }
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0,0,0,.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
